﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using MediaPortal.GUI.Library;
using MediaPortal.Database;
using MediaPortal.Configuration;
using SQLite.NET;

namespace MovingPicturesXML {
    public partial class SetupForm : Form {

        //values for / from config
        private bool SaveFile;
        private bool SaveFTP;
        private bool XSLHref;
        private bool MakeStatsNode;
        private bool MakeMovieList;
        private bool CustomXML;
        private bool UseXSLTransform;
        private string XSLTransformFile;
        private string XSLLocation = String.Empty;
        private string XMLSavePath = String.Empty;
        private string XMLSaveFileName = String.Empty;
        private string XMLCreateInterval = String.Empty;
        private string XMLDefaultSortBy = String.Empty;
        private string XMLDefaultSortDir = String.Empty;
        private string FTPServer = String.Empty;
        private string FTPUser = String.Empty;
        private string FTPPass = String.Empty;
        private string FTPPath = String.Empty;
        private string FTPFileName = String.Empty;
        private string CustomXMLList = String.Empty;

        // Default columns for customized listview
        List<String> selectedCols = new List<string>(MovingPicturesXML.defaultCols.Length);

        // Constructor
        public SetupForm() {
            // Initialize form
            InitializeComponent();

            // Check export methods
            if (!(ckbSaveToFile.Checked || ckbSaveToFTP.Checked)) {
                this.updateStatus("Select at least 1 export method.", Color.Orange);
            }

            // Assign default values to selectedCols list
            selectedCols.AddRange(MovingPicturesXML.defaultCols);

            // Display version in Window title
            Version v = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
            this.Text = "MovingPicturesXML v" + v.Major + "." + v.Minor + "." + v.Build + " - Configuration";
        }

        private void SetupForm_Load(object sender, EventArgs e) {
            // Build column list for custom xml selection
            SQLiteClient mp_db = new SQLiteClient(Config.GetFile(Config.Dir.Database, @"movingpictures.db3"));
            SQLiteResultSet results = mp_db.Execute("SELECT DISTINCT(T1.id), title, alternate_titles, sortby, directors, writers, actors, year, genres, certification, language, tagline, summary, score, popularity, date_added, runtime, imdb_id, alternatecovers, coverfullpath, coverthumbfullpath, backdropfullpath, details_url, T3.fullpath, T3.videoresolution, T3.videocodec, T3.audiocodec, T3.hassubtitles, T3.videoformat FROM movie_info T1 LEFT OUTER JOIN local_media__movie_info T2 on T1.id = T2.movie_info_id LEFT OUTER JOIN local_media T3 on T2.local_media_id = T3.id");
            results.ColumnNames.ForEach(AddListItem);

            // Default sort by = sortby ASC
            cmbSortBy.SelectedIndex = 3;
            cmbSortDir.SelectedIndex = 0;

            this.LoadSettings();
        }
        
        private void AddListItem(string item) {
            lstCols.Items.Add(item);
            cmbSortBy.Items.Add(item);
        }

        #region Button actions
        private void btnSaveFolder_Click(object sender, EventArgs e) {
            FolderBrowserDialog folder = new FolderBrowserDialog();
            folder.Description = "Select folder to save XML or HTML to.";
            folder.ShowNewFolderButton = true;
            folder.RootFolder = Environment.SpecialFolder.Desktop;
            folder.SelectedPath = @XMLSavePath;
            folder.ShowDialog();
            XMLSavePath = folder.SelectedPath;
            txtSavePath.Text = XMLSavePath;
        }

        private void btnSaveSettings_Click(object sender, EventArgs e) {
            this.SaveSettings();
            this.Close();
        }

        private void btnXSLTransformFile_Click(object sender, EventArgs e) {
            OpenFileDialog fileFind = new OpenFileDialog();
            fileFind.Title = "XSL file used to transform XML to HTML";
            fileFind.Multiselect = false;
            fileFind.Filter = "XSL files|*.xsl";
            fileFind.InitialDirectory = @XSLLocation;
            DialogResult res = fileFind.ShowDialog();
            XSLTransformFile = fileFind.FileName;
            
            if (XSLTransformFile.Length > 0) {
                txtXSLFileLocation.Text = XSLTransformFile;
            }
            fileFind.Dispose();
        }


        private void btnSelectAll_Click(object sender, EventArgs e) {
            foreach (ListViewItem lvi in lstCols.Items) {
                lvi.Checked = true;
            }
        }

        private void btnSelectNone_Click(object sender, EventArgs e) {
            foreach (ListViewItem lvi in lstCols.Items) {
                lvi.Checked = false;
            }

        }

        private void btnSelectDefault_Click(object sender, EventArgs e) {
            if (sender is Button) {
                if (((Button)sender).Name.Equals("btnSelectDefault")) {
                    selectedCols = new List<string>(MovingPicturesXML.defaultCols.Length);
                    selectedCols.AddRange(MovingPicturesXML.defaultCols);
                }

                foreach (ListViewItem lvi in lstCols.Items) {
                    lvi.Checked = selectedCols.Contains(lvi.Text);
                }

                // set default sort by selection
                cmbSortBy.SelectedIndex = 3;
                cmbSortDir.SelectedIndex = 0;
            }
        }

        private void btnSelectDetailed_Click(object sender, EventArgs e) {
            this.selectedCols = new List<string>(MovingPicturesXML.detailedCols.Length);
            this.selectedCols.AddRange(MovingPicturesXML.detailedCols);
            this.btnSelectDefault_Click(sender, e);

        }
        #endregion

        #region Checkbox changes
        private void ckbUseXSLTransform_CheckedChanged(object sender, EventArgs e) {
            if (ckbUseXSLTransform.Checked) {
                UseXSLTransform = true;
                btnXSLTransformFile.Enabled = true;
                txtXSLFileLocation.Enabled = true;

                // Automatically change filename extension on check
                txtFileName.Text = txtFileName.Text.Replace(".xml", ".html");
                txtFTPFileName.Text = txtFTPFileName.Text.Replace(".xml", ".html");
            }
            else {
                UseXSLTransform = false;
                btnXSLTransformFile.Enabled = false;
                txtXSLFileLocation.Enabled = false;

                // Automatically change filename extension on uncheck
                txtFileName.Text = txtFileName.Text.Replace(".html", ".xml");
                txtFTPFileName.Text = txtFTPFileName.Text.Replace(".html", ".xml");
            }
        }

        private void ckbXSLHref_CheckedChanged(object sender, EventArgs e) {
            if (ckbXSLHref.Checked) {
                XSLHref = true;
                txtXSLHref.ReadOnly = false;
            }
            else {
                XSLHref = false;
                txtXSLHref.ReadOnly = true;
                txtXSLHref.Text = String.Empty;
            }
        }

        private void ckbCustomList_CheckedChanged(object sender, EventArgs e) {
            if (ckbCustomList.Checked) {
                lstCols.Visible = true;
                btnSelectAll.Visible = btnSelectNone.Visible = btnSelectDefault.Visible = btnSelectDetailed.Visible = lblSelect.Visible = true;
                lblSortBy.Visible = cmbSortBy.Visible = cmbSortDir.Visible = lblSelect.Visible = true;
                CustomXML = true;
            }
            else {
                lstCols.Visible = false;
                btnSelectAll.Visible = btnSelectNone.Visible = btnSelectDefault.Visible = btnSelectDetailed.Visible = false;
                lblSortBy.Visible = cmbSortBy.Visible = cmbSortDir.Visible = lblSelect.Visible = false;
                CustomXML = false;
            }
        }

        private void lstCols_ItemChecked(object sender, ItemCheckedEventArgs e) {
            if (lstCols.CheckedItems.Count == 0) {
                this.updateStatus("Minimum 1 export value needed.", Color.Orange);
                this.btnSaveSettings.Enabled = this.btnForceExport.Enabled 
                    = this.exitConfigurationToolStripMenuItem.Enabled = this.manualToolStripMenuItem.Enabled = false;
            }
            else {
                this.btnSaveSettings.Enabled = this.btnForceExport.Enabled 
                    = this.exitConfigurationToolStripMenuItem.Enabled = this.manualToolStripMenuItem.Enabled = true;
                this.updateStatus("Ready 2 Export...", Color.Gray);
            }
        }

        private void ckbStatsNode_CheckedChanged(object sender, EventArgs e) {
            if (ckbStatsNode.Checked) {
                MakeStatsNode = true;
            }
            else {
                MakeStatsNode = false;
            }
        }

        private void ckbMakeMovieList_CheckedChanged(object sender, EventArgs e) {
            if (ckbMakeMovieList.Checked) {
                MakeMovieList = ckbCustomList.Enabled = lstCols.Enabled = cmbSortBy.Enabled = cmbSortDir.Enabled 
                = btnSelectAll.Enabled = btnSelectNone.Enabled = btnSelectDefault.Enabled = btnSelectDetailed.Enabled = true;
            }
            else {
                MakeMovieList = ckbCustomList.Enabled = lstCols.Enabled = cmbSortBy.Enabled = cmbSortDir.Enabled
                = btnSelectAll.Enabled = btnSelectNone.Enabled = btnSelectDefault.Enabled = btnSelectDetailed.Enabled = false;
            }
        }

        private void ckbSaveToFTP_CheckedChanged(object sender, EventArgs e) {
            if (ckbSaveToFTP.Checked) {
                SaveFTP = btnForceExport.Enabled = manualToolStripMenuItem.Enabled = true;
                txtFTPServer.ReadOnly = txtFTPPassword.ReadOnly = txtFTPUserName.ReadOnly = txtFTPPath.ReadOnly = txtFTPFileName.ReadOnly = false;
                this.updateStatus("Verify FTP settings before exporting...", Color.Gray);
            }
            else {
                btnForceExport.Enabled = manualToolStripMenuItem.Enabled = ckbSaveToFile.Checked;
                txtFTPServer.ReadOnly = txtFTPPassword.ReadOnly = txtFTPUserName.ReadOnly = txtFTPPath.ReadOnly = txtFTPFileName.ReadOnly = true;
                if (!ckbSaveToFile.Checked) this.updateStatus("Select at least 1 export method.", Color.Orange);
                SaveFTP = false;
            }
        }

        private void ckbSaveToFile_CheckedChanged(object sender, EventArgs e) {
            if (ckbSaveToFile.Checked) {
                SaveFile = btnSaveFolder.Enabled = btnForceExport.Enabled = manualToolStripMenuItem.Enabled = true;
                txtSavePath.ReadOnly = txtFileName.ReadOnly = false;
                this.updateStatus("Verify local file settings before exporting...", Color.Gray);
            }
            else {
                btnForceExport.Enabled = manualToolStripMenuItem.Enabled = ckbSaveToFTP.Checked;
                SaveFile = btnSaveFolder.Enabled = false;
                txtSavePath.ReadOnly = txtFileName.ReadOnly = true;
                if (!ckbSaveToFTP.Checked) this.updateStatus("Select at least 1 export method.", Color.Orange);
            }
        }
        #endregion

        #region Load / Save config
        private void LoadSettings() {
            try {
                using (MediaPortal.Profile.Settings xmlreader = new MediaPortal.Profile.Settings("MediaPortal.xml")) {
                    SaveFile = xmlreader.GetValueAsBool("MovingPicturesXML", "SaveFile", false);
                    SaveFTP = xmlreader.GetValueAsBool("MovingPicturesXML", "SaveFTP", false);
                    XSLHref = xmlreader.GetValueAsBool("MovingPicturesXML", "XSLHref", false);
                    CustomXML = xmlreader.GetValueAsBool("MovingPicturesXML", "CustomXML", false);
                    UseXSLTransform = xmlreader.GetValueAsBool("MovingPicturesXML", "UseXSLTransform", false);
                    MakeMovieList = xmlreader.GetValueAsBool("MovingPicturesXML", "MakeMovieList", true);
                    MakeStatsNode = xmlreader.GetValueAsBool("MovingPicturesXML", "MakeStatsNode", true);
                    CustomXMLList = xmlreader.GetValueAsString("MovingPicturesXML", "CustomXMLList", String.Empty);
                    XSLLocation = xmlreader.GetValueAsString("MovingPicturesXML", "XSLLocation", String.Empty);
                    XSLTransformFile = xmlreader.GetValueAsString("MovingPicturesXML", "XSLTransformFile", String.Empty);
                    XMLCreateInterval = xmlreader.GetValueAsString("MovingPicturesXML", "XMLCreateInterval", "60");
                    XMLSavePath = xmlreader.GetValueAsString("MovingPicturesXML", "XMLSavePath", String.Empty);
                    XMLSaveFileName = xmlreader.GetValueAsString("MovingPicturesXML", "XMLSaveFileName", "Moving-PicturesXML.xml");
                    XMLDefaultSortBy = xmlreader.GetValueAsString("MovingPicturesXML", "XMLDefaultSortBy", "sortby");
                    XMLDefaultSortDir = xmlreader.GetValueAsString("MovingPicturesXML", "XMLDefaultSortDir", "ASC");
                    FTPServer = xmlreader.GetValueAsString("MovingPicturesXML", "FTPServer", String.Empty);
                    FTPUser = xmlreader.GetValueAsString("MovingPicturesXML", "FTPUser", String.Empty);
                    FTPPass = xmlreader.GetValueAsString("MovingPicturesXML", "FTPPass", String.Empty);
                    FTPPath = xmlreader.GetValueAsString("MovingPicturesXML", "FTPPath", String.Empty);
                    FTPFileName = xmlreader.GetValueAsString("MovingPicturesXML", "FTPFileName", "Moving-PicturesXML.xml");

                    txtFTPPassword.Text = FTPPass; 
                    txtFTPServer.Text = FTPServer; 
                    txtFTPUserName.Text = FTPUser;
                    txtFTPFileName.Text = FTPFileName;
                    txtFTPPath.Text = FTPPath;
                    txtSavePath.Text = XMLSavePath;
                    txtFileName.Text = XMLSaveFileName;
                    txtTime.Text = XMLCreateInterval;
                    txtXSLHref.Text = XSLLocation;
                    txtXSLFileLocation.Text = XSLTransformFile;
                    cmbSortBy.SelectedIndex = cmbSortBy.FindString(XMLDefaultSortBy);
                    cmbSortDir.SelectedIndex = cmbSortDir.FindString(XMLDefaultSortDir);

                    string[] checkedItems = CustomXMLList.Split(new Char[]{';'});

                    foreach (ListViewItem item in lstCols.Items) {
                        foreach (string checkedItem in checkedItems) {
                            if (item.Text == checkedItem == true) {
                                item.Checked = true;
                            }
                        }
                    }
                    CustomXMLList = String.Empty;
                    
                    if (SaveFile) { ckbSaveToFile.Checked = true; }
                    if (SaveFTP) { ckbSaveToFTP.Checked = true; }
                    if (XSLHref) { ckbXSLHref.Checked = true; }
                    if (CustomXML) { ckbCustomList.Checked = true; }
                    if (MakeStatsNode) { ckbStatsNode.Checked = true; }
                    if (MakeMovieList) { ckbMakeMovieList.Checked = true; }
                    if (UseXSLTransform) { ckbUseXSLTransform.Checked = true; }
                }
            }
            catch (Exception ex) {
                Log.Error("MovingPicturesXML - LoadSettings(): {0}", ex.Message);
            }
        }

        private void btnForceExport_Click(object sender, EventArgs e) {
            this.btnForceExport.Enabled = false;
            this.updateStatus("Exporting...", Color.Orange);
            this.SaveSettings();
            Log.Info("Exporting movie list manually...");
            MovingPicturesXML mpxml = new MovingPicturesXML();
            mpxml.Start();
            mpxml.MakeXML();
            mpxml.Stop();
            this.btnForceExport.Enabled = true;
            this.updateStatus("Manual Export successful.", Color.ForestGreen);
            Log.Info("Manually exporting movie list was successful.");
        }

        private void SaveSettings() {
            // clear variable
            CustomXMLList = String.Empty;
            foreach (ListViewItem selectedItem in lstCols.CheckedItems) {
                CustomXMLList += selectedItem.Text + ";";
            }

            try {
                using (MediaPortal.Profile.Settings xmlwriter = new MediaPortal.Profile.Settings("MediaPortal.xml")) {
                    xmlwriter.SetValueAsBool("MovingPicturesXML", "SaveFile", SaveFile);
                    xmlwriter.SetValueAsBool("MovingPicturesXML", "SaveFTP", SaveFTP);
                    xmlwriter.SetValueAsBool("MovingPicturesXML", "XSLHref", XSLHref);
                    xmlwriter.SetValueAsBool("MovingPicturesXML", "CustomXML", CustomXML);
                    xmlwriter.SetValueAsBool("MovingPicturesXML", "MakeStatsNode", MakeStatsNode);
                    xmlwriter.SetValueAsBool("MovingPicturesXML", "MakeMovieList", MakeMovieList);
                    xmlwriter.SetValueAsBool("MovingPicturesXML", "UseXSLTransform", UseXSLTransform);
                    xmlwriter.SetValue("MovingPicturesXML", "XSLTransformFile", XSLTransformFile);
                    xmlwriter.SetValue("MovingPicturesXML", "CustomXMLList", CustomXMLList);
                    xmlwriter.SetValue("MovingPicturesXML", "XSLLocation", txtXSLHref.Text);
                    xmlwriter.SetValue("MovingPicturesXML", "XMLCreateInterval", txtTime.Text);
                    xmlwriter.SetValue("MovingPicturesXML", "XMLSavePath", XMLSavePath);
                    xmlwriter.SetValue("MovingPicturesXML", "XMLSaveFileName", txtFileName.Text);
                    xmlwriter.SetValue("MovingPicturesXML", "XMLDefaultSortBy", cmbSortBy.Text);
                    xmlwriter.SetValue("MovingPicturesXML", "XMLDefaultSortDir", cmbSortDir.Text);
                    xmlwriter.SetValue("MovingPicturesXML", "FTPServer", txtFTPServer.Text);
                    xmlwriter.SetValue("MovingPicturesXML", "FTPUser", txtFTPUserName.Text);
                    xmlwriter.SetValue("MovingPicturesXML", "FTPPass", txtFTPPassword.Text);
                    xmlwriter.SetValue("MovingPicturesXML", "FTPPath", txtFTPPath.Text);
                    xmlwriter.SetValue("MovingPicturesXML", "FTPFileName", txtFTPFileName.Text);
                }
            }
            catch (Exception ex) {
                Log.Error("MovingPicturesXML - SaveSettings(): {0}", ex.Message);
            }
        }

        private void btnClose_Click(object sender, EventArgs e) {
            this.Close();
        }

        private void updateStatus(String msg, Color clr) {
            this.txtStatus.Text = msg;
            this.txtStatus.ForeColor = clr;
            Application.DoEvents();
        }
        #endregion

        #region Menu Actions
        private void aboutToolStripMenuItem_Click(object sender, EventArgs e) {
            Popups.AboutPopup about = new Popups.AboutPopup();
            about.ShowDialog();
        }

        private void exitConfigurationToolStripMenuItem_Click(object sender, EventArgs e) {
            this.btnSaveSettings_Click(sender, e);
            this.btnClose_Click(sender, e);
        }
        #endregion
    }
}
